package com.question.business.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.question.business.user.entity.UserRole;
import com.question.business.user.mapper.UserRoleMapper;
import com.question.business.user.service.IUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 用户角色服务实现类
 *
 * @author star
 * @since 2023-09-13
 */
@Slf4j
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {


    /**
     * 用户角色分页查询
     *
     * @param userId 用户ID
     * @return List<String> 响应参数
     */
    @Override
    public List<String> queryRoleByUserId(String userId) {
        return baseMapper.queryRoleByUserId(userId);
    }

    /**
     * 角色用户查询
     *
     * @param roleId 角色ID
     * @return List<String> 响应参数
     */
    @Override
    public List<String> queryUserByRoleId(String roleId) {
        return baseMapper.queryUserByRoleId(roleId);
    }

    /**
     * 用户角色新增数据
     *
     * @param userId  用户ID
     * @param roleIds 角色ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUserRole(String userId, List<String> roleIds) {
        // 删除用户角色
        baseMapper.deleteByUserId(userId);
        handleBatchAdd(Collections.singletonList(userId), roleIds);
    }

    /**
     * 处理批量保存
     *
     * @param userIds 用户ID
     * @param roleIds 角色ID
     */
    private void handleBatchAdd(List<String> userIds, List<String> roleIds) {
        if (CollectionUtils.isNotEmpty(userIds) && CollectionUtils.isNotEmpty(roleIds)) {
            List<UserRole> data = new ArrayList<>();
            for (String userId : userIds) {
                for (String roleId : roleIds) {
                    UserRole entity = new UserRole();
                    entity.setUserId(userId);
                    entity.setRoleId(roleId);
                    data.add(entity);
                }
            }
            super.saveBatch(data);
        }
    }

    /**
     * 角色用户新增数据
     *
     * @param roleId  角色ID
     * @param userIds 用户ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addRoleUser(String roleId, List<String> userIds) {
        // 删除角色用户
        baseMapper.deleteByRoleId(roleId);
        handleBatchAdd(userIds, Collections.singletonList(roleId));
    }
}